<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <title>JS 图层拖拽</title>
    <style>
        #box{
            border:1px solid;
            width:100px;
            height:100px;
            background-color:orange;
            position:absolute;
            top:100px;
            left:100px;
        }
    </style>
</head>
<body>
    <h1>JS 图层拖拽</h1>
    <hr>
    <div id="box"></div>

    <script>
        box.onmousedown = function(en){
            var en = en||window.event;
            this.style.backgroundColor = "blue";
            // 获取鼠标的相对于图形位置;以便后面 可以让图形根据鼠标进行移动
            var top = en.offsetY;
            var left = en.offsetX;
            // 移动
            document.onmousemove = function(env){
                var env = env || window.event;
                var dtop = env.y-left;
                var dleft = env.x - top;
                box.style.left = dleft + 'px';
                box.style.top = dtop + 'px';

            }

        }

        //松开
        document.onmouseup = function(){
            box.style.backgroundColor = "orange";
            document.onmousemove = null;
        }

    </script>
    

</body>
</html>